package mobileann.mafamily.utils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import org.json.JSONObject;

import com.mofind.android.net.HttpUtils;
import com.mofind.android.net.JSONParser;
import com.mofind.android.net.HttpUtils.HttpResultCallback;

import mobileann.mafamily.act.eye.LockActivity;
import mobileann.mafamily.act.main.FS;
import mobileann.mafamily.db.model.WeekPlanDBModel;
import mobileann.mafamily.entity.WeekPlanBean;
import mobileann.mafamily.model.UDPSocket;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

/**
 * 周计划管理类
 * <br> 锁屏计划
 * @author doubleT
 * 
 *         与后台通讯，实现增删改查
 */
public class WeekPlanManager {

	private Context c;
	private UDPSocket socket;
	public static final int ADDPLAN_SUCCESS=741;
	public static final int ADDPLAN_ERROR=742;
	public static final int UPDATEPLAN_SUCCESS=743;
	public static final int UPDATEPLAN_ERROR=744;
	public static final int DELPLAN_SUCCESS=745;
	public static final int DELPLAN_ERROR=746;
	public WeekPlanManager(Context c) {
		this.c = c;
		socket = UDPSocket.getInstance(c);
	}

	/**
	 * 2.9添加锁机策略
	 * 
	 * @param WeekPlanBean
	 */
	public void addWeekPlan(WeekPlanBean plan) {

		if (plan.getFamily_id() == null) {
			ToastShow("Family_id is null");
			return;
		}

		if (plan.getUser_id() == null) {
			ToastShow("getUser_id is null");
			return;
		}

		if (plan.getTarget_id() == null) {
			ToastShow("getTarget_id is null");
			return;
		}

		if (plan.getStart_time() == null) {
			ToastShow("getStart_time is null");
			return;
		}

		if (plan.getEnd_time() == null) {
			ToastShow("getEnd_time is null");
			return;
		}

		if (plan.getWeek() == null) {
			ToastShow("getWeek is null");
			return;
		}

		if (plan.getEnabled() == null) {
			ToastShow("getEnabled is null");
			return;
		}

		socket.add_LockPhone_Strategy(plan.getFamily_id(), plan.getUser_id(),
				plan.getTarget_id(), plan.getStart_time(), plan.getEnd_time(),
				plan.getWeek(), "0");

	}

	/**
	 * 2.9a批量添加锁机策略
	 * 
	 * @param List
	 *            <WeekPlanBean>
	 */
	public void addWeekPlan(List<WeekPlanBean> planlist) {
		List<Map<String, Object>> maps = null;
		Map<String, Object> map = null;
		if (planlist.size() > 0) {
			maps = new ArrayList<Map<String, Object>>();

			planlist.get(0).getFamily_id();
			planlist.get(0).getUser_id();
			planlist.get(0).getTarget_id();

			for (int i = 0; i < planlist.size(); i++) {
				map = new HashMap<String, Object>();
				map.put("starttime", planlist.get(i).getStart_time());
				map.put("stoptime", planlist.get(i).getEnd_time());
				map.put("WeekDay", planlist.get(i).getWeek());
				map.put("Enabled", "1");
				maps.add(map);
			}

			socket.add_LockPhone_Strategy_All(planlist.get(0).getFamily_id(),
					planlist.get(0).getUser_id(), planlist.get(0)
					.getTarget_id(), maps);

		}

	}

	/**
	 * 2.11删除锁机策略
	 * 
	 * @param WeekPlanBean
	 */
	public void deleteWeekPlan(WeekPlanBean plan) {

		if (plan.getFamily_id() == null) {
			ToastShow("Family_id is null");
			return;
		}

		if (plan.getUser_id() == null) {
			ToastShow("getUser_id is null");
			return;
		}

		if (plan.getTarget_id() == null) {
			ToastShow("getTarget_id is null");
			return;
		}

		if (plan.getPlan_id() == null) {
			ToastShow("getPlan_id is null");
			return;
		}

		socket.delete_LockPhone_Strategy(plan.getFamily_id(),
				plan.getUser_id(), plan.getTarget_id(), plan.getPlan_id());
	}

	/**
	 * 2.10修改锁机策略
	 * 
	 * @param WeekPlanBean
	 */
	public void changeWeekPlan(WeekPlanBean plan) {

		if (plan.getFamily_id() == null) {
			ToastShow("Family_id is null");
			return;
		}

		if (plan.getUser_id() == null) {
			ToastShow("getUser_id is null");
			return;
		}

		if (plan.getTarget_id() == null) {
			ToastShow("getTarget_id is null");
			return;
		}

		if (plan.getPlan_id() == null) {
			ToastShow("getPlan_id is null");
			return;
		}

		if (plan.getStart_time() == null) {
			ToastShow("getStart_time is null");
			return;
		}

		if (plan.getEnd_time() == null) {
			ToastShow("getEnd_time is null");
			return;
		}

		if (plan.getWeek() == null) {
			ToastShow("getWeek is null");
			return;
		}

		if (plan.getEnabled() == null) {
			ToastShow("getEnabled is null");
			return;
		}

		socket.change_LockPhone_Strategy(plan.getFamily_id(),
				plan.getUser_id(), plan.getTarget_id(), plan.getPlan_id(),
				plan.getStart_time(), plan.getEnd_time(), plan.getWeek(),
				plan.getEnabled());
	}

	/**
	 * 2.12读取锁机策略
	 * 
	 * @param aFID
	 * @param aUID
	 * @param aTID
	 */
	public void loadWeekPlan(String aFID, String aUID, String aTID) {

		socket.loadLockstrategy(aFID, aUID, aTID);// 返回数据

	}

	/**
	 * 2.13宝贝端读取锁机策略
	 * 
	 * @param aFID
	 * @param aUID
	 */
	public void loadWeekPlanByBaby(String aFID, String aUID) {

	}
	/**
	 * 检测本地锁频策略
	 * 
	 * @param str
	 */

	private boolean lockPlanTag=false;
	public void loopWeekPlan(Map<String, String> map) {
		lockPlanTag = false;
		List<WeekPlanBean> planList = WeekPlanDBModel.queryAll(c);
		Calendar calendar = Calendar.getInstance(TimeZone
				.getTimeZone("GMT+8:00"));
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);
		if(hour==00 && minute==00){
			for(int i = 0; i < planList.size(); i++){
				SPUtils.setWeekPlanClose(planList.get(i).getPlan_id(), planList.get(i).getWeek(), planList.get(i).getStart_time(),planList.get(i).getEnd_time(), true);
			}
		}

		for (int i = 0; i < planList.size(); i++) {
			if (planList.get(i).getEnabled().equals("1")) {
				int week = calendar.get(Calendar.DAY_OF_WEEK);
				int week_cn = 0;
				switch (week) {
				case 1:
					week_cn = 7;
					break;
				case 2:
					week_cn = 1;
					break;
				case 3:
					week_cn = 2;
					break;
				case 4:
					week_cn = 3;
					break;
				case 5:
					week_cn = 4;
					break;
				case 6:
					week_cn = 5;
					break;
				case 7:
					week_cn = 6;
					break;
				}
				String week_str = planList.get(i).getWeek();
				Log.i("loopWeekPlan", week_str);
				if (week_str.indexOf(week_cn + "") != -1) {
					int h = calendar.get(Calendar.HOUR_OF_DAY);
					int m = calendar.get(Calendar.MINUTE);
					int t = h * 60 + m;
					int sh = Integer.parseInt(planList.get(i).getStart_time()
							.substring(0, 2));
					int sm = Integer.parseInt(planList.get(i).getStart_time()
							.substring(3, 5));
					int st = sh * 60 + sm;
					int eh = Integer.parseInt(planList.get(i).getEnd_time()
							.substring(0, 2));
					int em = Integer.parseInt(planList.get(i).getEnd_time()
							.substring(3, 5));
					int et = eh * 60 + em;
					if(t>st&& t < et){
						lockPlanTag=true;
					}
					if (t > st && t < et && SPUtils.isWeekPlanClose(planList.get(i).getPlan_id(), planList.get(i).getWeek(), planList.get(i).getStart_time(),planList.get(i).getEnd_time())) {
						//                        lockPlanTag = true;
						FS.lockPlanTag=true;
						SPUtils.setWeekPlanClose(planList.get(i).getPlan_id(), planList.get(i).getWeek(), planList.get(i).getStart_time(),planList.get(i).getEnd_time(), false);
						if(SPUtils.getWeekPlanTime().equals(planList.get(i).getPlan_id()+ planList.get(i).getWeek()+ planList.get(i).getStart_time()+planList.get(i).getEnd_time())){
							SPUtils.setCanShowAuthTips(false);
						}else{
							SPUtils.setWeekPlanTime(planList.get(i).getPlan_id(), planList.get(i).getWeek(), planList.get(i).getStart_time(),planList.get(i).getEnd_time());
							SPUtils.setCanShowAuthTips(true);
						}
						break;
					}
				}
			}
		}
		if (FS.lockPlanTag && lockPlanTag) {
			LockActivity.lockPhone(map);
		} else {
			if (!SPUtils.getIsLockedByHand()) {
				LockActivity.unLockPhone(map);
				FS.lockPlanTag=false;
			}
		}

	}

	private void ToastShow(String str) {
		Toast.makeText(c, str, Toast.LENGTH_SHORT).show();
	}
	private Map<String, String> getAddPlanPara(String target_uid,String start_time,String stop_time,String week,String enabled) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("from", "add_policy");
		map.put("uid", SPUtils.getMySelf(SPUtils.MYUID));
		map.put("data", addData(target_uid, start_time, stop_time, week, enabled));
		return map;
	}
	private String addData(String target_uid,String start_time,String stop_time,String week,String enabled){
		Map<String, String> map = new HashMap<String, String>();
		map.put("uid", SPUtils.getMySelf(SPUtils.MYUID));
		map.put("target_uid", target_uid);
		map.put("start_time", start_time);
		map.put("stop_time", stop_time);
		map.put("week", week);
		map.put("enabled", enabled);
		String data = MyTaskUtils.getInstance().map2json(map);
		return TripleDESUtil.CBCEncode(SPUtils.getMySelf(SPUtils.MYUID),SPUtils.getMySelf(SPUtils.MYURAD), data);
	}
	public void doAddPlanPolicy(String target_uid,String start_time,String stop_time,String week,String enabled,final Handler handler){
		HttpUtils.startHttpPost(URLUtils.URL_GROWTH_UPLOAD, getAddPlanPara(target_uid, start_time, stop_time, week, enabled), new HttpResultCallback() {

			@Override
			public void result(String url, boolean isResult, String jsonStr) {
				// TODO Auto-generated method stub
				if(isResult){
					String json = TripleDESUtil.getJsonObjStr(SPUtils.getMySelf(SPUtils.MYUID),
							SPUtils.getMySelf(SPUtils.MYURAD), jsonStr);
					if(!TextUtils.isEmpty(json)){
						JSONObject jo = JSONParser.getJSONObject(json);
						String status=JSONParser.getString(jo, "status");
						if("true".equals(status)){
							if(handler!=null){
								handler.obtainMessage(ADDPLAN_SUCCESS).sendToTarget();
							}
						}else{
							if(handler!=null){
								handler.obtainMessage(ADDPLAN_ERROR).sendToTarget();
							}
						}
					}else{
						if(handler!=null){
							handler.obtainMessage(ADDPLAN_ERROR).sendToTarget();
						}
					}
				}
			}
		});
	}
	private Map<String, String> getUpdatePlanPara(String target_uid,String planId,String start_time,String stop_time,String week,String enabled) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("from", "update_policy");
		map.put("uid", SPUtils.getMySelf(SPUtils.MYUID));
		map.put("data", updateData(target_uid,planId, start_time, stop_time, week, enabled));
		Log.i("changeplan","LLL"+map.toString());
		return map;
	}
	private String updateData(String target_uid,String planId,String start_time,String stop_time,String week,String enabled){
		Map<String, String> map = new HashMap<String, String>();
		map.put("uid", SPUtils.getMySelf(SPUtils.MYUID));
		map.put("target_uid", target_uid);
		map.put("pid", planId);
		map.put("start_time", start_time);
		map.put("stop_time", stop_time);
		map.put("week", week);
		map.put("enabled", enabled);
		String data = MyTaskUtils.getInstance().map2json(map);
		return TripleDESUtil.CBCEncode(SPUtils.getMySelf(SPUtils.MYUID),SPUtils.getMySelf(SPUtils.MYURAD), data);
	}
	public void doUpdatePlanPolicy(String target_uid,String planId,String start_time,String stop_time,String week,String enabled,final Handler handler){
		HttpUtils.startHttpPost(URLUtils.URL_GROWTH_UPLOAD, getUpdatePlanPara(target_uid,planId, start_time, stop_time, week, enabled), new HttpResultCallback() {

			@Override
			public void result(String url, boolean isResult, String jsonStr) {
				if(isResult){
					String json = TripleDESUtil.getJsonObjStr(SPUtils.getMySelf(SPUtils.MYUID),
							SPUtils.getMySelf(SPUtils.MYURAD), jsonStr);
					if(!TextUtils.isEmpty(json)){
						JSONObject jo = JSONParser.getJSONObject(json);
						String status=JSONParser.getString(jo, "status");
						if("true".equals(status)){
							if(handler!=null){
								handler.obtainMessage(UPDATEPLAN_SUCCESS).sendToTarget();
							}
						}else{
							if(handler!=null){
								handler.obtainMessage(UPDATEPLAN_ERROR).sendToTarget();
							}
						}
					}else{
						if(handler!=null){
							handler.obtainMessage(UPDATEPLAN_ERROR).sendToTarget();
						}
					}
				}
			}
		});
	}
	private Map<String, String> getDelPlanPara(String target_uid,String planId) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("from", "delete_policy");
		map.put("uid", SPUtils.getMySelf(SPUtils.MYUID));
		map.put("data", delData(target_uid,planId));
		return map;
	}
	private String delData(String target_uid, String planId){
		Map<String, String> map = new HashMap<String, String>();
		map.put("uid", SPUtils.getMySelf(SPUtils.MYUID));
		map.put("target_uid", target_uid);
		map.put("pid", planId);
		String data = MyTaskUtils.getInstance().map2json(map);
		return TripleDESUtil.CBCEncode(SPUtils.getMySelf(SPUtils.MYUID),SPUtils.getMySelf(SPUtils.MYURAD), data);
	}
	public void doDelPlanPolicy(String target_uid,String planId,final Handler handler){
		HttpUtils.startHttpPost(URLUtils.URL_GROWTH_UPLOAD, getDelPlanPara(target_uid,planId), new HttpResultCallback() {

			@Override
			public void result(String url, boolean isResult, String jsonStr) {
				if(isResult){
					String json = TripleDESUtil.getJsonObjStr(SPUtils.getMySelf(SPUtils.MYUID),
							SPUtils.getMySelf(SPUtils.MYURAD), jsonStr);
					if(!TextUtils.isEmpty(json)){
						JSONObject jo = JSONParser.getJSONObject(json);
						String status=JSONParser.getString(jo, "status");
						if("true".equals(status)){
							if(handler!=null){
								handler.obtainMessage(DELPLAN_SUCCESS).sendToTarget();
							}
						}else{
							if(handler!=null){
								handler.obtainMessage(DELPLAN_ERROR).sendToTarget();
							}
						}
					}else{
						if(handler!=null){
							handler.obtainMessage(DELPLAN_ERROR).sendToTarget();
						}
					}
				}
			}
		});
	}
}
